﻿//Copyright 2008 Kristian Gundry And Rune Juhl-Petersen
//This file is part of Plain.

//Plain is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//any later version.

//Plain is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Lesser General Public License for more details.

//You should have received a copy of the GNU Lesser General Public License
//along with Plain.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Plain.Data;
using System.Reflection; 
using Plain.Utilities.Reflection;

namespace Plain.Web.Mvc.Binders {
    public class PlainBinder<T, TT> : IModelBinder where T: IBusinessEntity<TT>, new () {

        #region Methods

        /// <summary>
        /// Gets an instance of the type of T
        /// </summary>
        /// <param name="id">the id of the unique object</param>
        /// <returns>An instance of type T</returns>
        private T GetInstance(string id) {
            T instance;
            if (string.IsNullOrEmpty(id) || id.Equals(default(TT))) {
                instance = new T();
            } else {
                TT idValue = (TT)Convert.ChangeType(id, typeof(TT), null);
                ISearchableDao<T, TT> d = PlainApplication.Config.DaoFactory.GetDao<T, TT>();
                instance = d.Get(idValue);
            }
            return instance;
        }

        #endregion

        #region IModelBinder Members

        /// <summary>
        /// Binds the model
        /// </summary>
        /// <param name="controllerContext">mvc controller context</param>
        /// <param name="bindingContext">mvc binding context</param>
        /// <returns>the bound object</returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

            T instance = GetInstance(controllerContext.RouteData.Values["id"].ToString());

            bindingContext.ModelMetadata.Model = instance;
            IModelBinder defaultBinder = ModelBinders.Binders.DefaultBinder;

            object model = defaultBinder.BindModel(controllerContext, bindingContext);

            return model; 
        }

        #endregion
    }
}